import string
import urllib
import logging
import os

from google.appengine.ext import db
from google.appengine.api import mail

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _

from adrianremembersme import AdrianRemembersMe
from adrianremembersmeapp.models import LoginRecord, Member

def mainpage(request):
    return render_to_response('index.html', {})

def member(request):
    if request.method == "GET":
        template_values = {}
        
        if request.COOKIES.has_key('ack'):
            template_values['name'] = request.COOKIES['ack']

        return render_to_response("member.html", template_values)
    
    elif request.method == "POST":
        arm = AdrianRemembersMe()
        
        errcode = arm.ERROR_OK
        errmsg = ""
        cookie = ""
        
        template_values = {}
        
        try:
            tname = string.strip(request.REQUEST['name'])
            temail = string.strip(request.REQUEST['email'])
            tpassword = string.strip(request.REQUEST['password'])
    
            if (request.FILES.has_key('file') and request.FILES['file'].name):
                filedata = request.FILES['file'].read()
                filename = request.FILES['file'].name
                errcode = arm.membercreate(tname, tpassword, tname, temail, filedata, filename)
            else:
                errcode = arm.membercreate(tname, tpassword, tname, temail)
                
            if errcode != arm.ERROR_OK:
                if errcode == arm.ERROR_EMAIL_BAD:
                    errmsg = "bad email"    
                elif errcode == arm.ERROR_EMAIL_USED:
                    errmsg = "sorry, email already in use for another account"
                elif errcode == arm.ERROR_PASSWORD_WEAK:
                    errmgs = "password not long enough"
                elif errcode == arm.ERROR_USERNAME_NONE:
                    errmsg = "missing username"
                elif errcode == arm.ERROR_USERNAME_TAKEN:
                    errmsg = "username already taken, please try another"
                
            template_values['nameencoded'] = tname
            
        except KeyError:
            errmsg = "missing information"
            template_values['errmsg'] = errmsg
        
            return render_to_response("memberprocess.html", template_values)            

        template_values['errmsg'] = errmsg
        response = render_to_response("memberprocess.html", template_values)            
        
        if errcode == arm.ERROR_OK:
            arm.memberlogin(response, tname, tpassword, request.REQUEST.has_key('rememberme'))

        return response

def login(request):
    if request.method == "GET":
        if request.REQUEST.has_key('oldulr'):
            oldurl = request.REQUEST['oldurl']
        else:
            oldurl = "/"
        
        template_values = {'oldurl': oldurl}
        
        if request.REQUEST.has_key('errormsg'):
            template_values['errormsg'] = "Bad e-mail/password combination"
            
        return render_to_response("login.html", template_values)
    elif request.method == "POST":
        # check if pwd ok, look up user by username
        arm = AdrianRemembersMe()
        error = False
        oldurl = ""
        cookie = ""
        
        try:
            membername = request.REQUEST['name']
            password = request.REQUEST['password']
                
            if request.REQUEST.has_key('oldurl'):
                oldurl = request.REQUEST['oldurl']
            else:
                oldurl = "/"
                            
        except KeyError:
            error = True
        
        response = None
        
        if error:
            response = HttpResponseRedirect("/login?" + urllib.urlencode({"oldurl":oldurl, "error":error}, False))
        else:
            response = HttpResponseRedirect(oldurl)
            arm.memberlogin(response, membername, password, request.REQUEST.has_key('rememberme'))
                            
        return response
    
def logout(request):
    # todo: function to deliver cookieval
    arm = AdrianRemembersMe()
    response = HttpResponseRedirect("/")
    
    if request.COOKIES.has_key('ack'):
        cookieval = urllib.unquote(request.COOKIES['ack'])
        #empty cookie
        # todo: parametrize expiry date et al?
        
        #empty login from db
        arm.logincookieclear(cookieval)
        
        response.set_cookie('ack', "", expires="Fri, 31-Dec-2030 23:59:59 GMT")
        
        return response
    else:
        return response
        
def memberlist(request):
    arm = AdrianRemembersMe()
    members = arm.membergetlist()
                
    template_values = {'memberlist':members}
            
    return render_to_response("memberlist.html", template_values)

def getimage(request):
    arm = AdrianRemembersMe()
    membername = request.REQUEST['member']
    mem = arm.memberget(membername)
    
    #Is this meant to be for single image or multiimage?
    if mem:
        for memphoto in mem.photo_set:
            if request.REQUEST.has_key('size') and request.REQUEST['size'] == "thumb":
                return HttpResponse(memphoto.thumb, mimetype="image/png")
            else:
                return HttpResponse(memphoto.content, mimetype="image/jpeg")

def logintest(request):
    arm = AdrianRemembersMe()
    member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))

    template_values = {}

    if member:
        template_values['name'] = member.name
    else:
        template_values['name'] = _("-- no member ") + request.COOKIES['ack']
        
    return render_to_response("logintest.html", template_values)

def changepassword(request):
    if request.method == "GET":
        # present form
        arm = AdrianRemembersMe()
        member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))

        template_values = {'name':member.name}
        
        return render_to_response("changepassword.html", template_values)
    elif request.method == "POST":
        # look up user;
        arm = AdrianRemembersMe()
        cookieval = urllib.unquote(request.COOKIES['ack'])
        member = arm.membergetloggedin(cookieval)
        
        template_values = {}
        
        if member:
            if arm.validatepassword(member,request.REQUEST['oldpassword']):
                if request.REQUEST['newpassword'] == request.REQUEST['newpasswordconfirm']:
                    arm.loginclearmember(member, cookieval)
                    newpassword = request.REQUEST['newpassword']
                    error = arm.memberchangepassword(member, newpassword)
                
                    if error == arm.ERROR_OK:
                        template_values['message'] = _("password changed")
                        
                else:
                    template_values['message'] = _("new password wasn't typed in right, please go back and fix.")
            else:
                template_values['message'] = _("old password wasn't right.")
        
        return render_to_response("changepasswordprocess.html", template_values) 

def forgotpassword(request):
    template = "forgotpassword.html"
    template_values = {}
        
    if request.method == "POST":
        memberemail = request.REQUEST['email']
        if memberemail == '':
            template_values['error'] = 'Please type in your email'
        
        else:
            arm = AdrianRemembersMe()
            resetpath = os.path.join(request.build_absolute_uri(),'resetpassword/')
            success = arm.forgotpassword(memberemail,resetpath)
            if success:
                template_values['success'] = 'True'
            else:
                template_values['error'] = 'The email you typed is not associated with an existing account.'
            
    return render_to_response(template, template_values)

def resetpassword(request,offset):
    template = "resetpassword.html"
    template_values = {}
    #Get Reset Code
    if request.method == "GET":
        code = offset
    elif request.method == "POST":
        code = request.REQUEST['code']
    #Validate Reset Code
    if code:
        arm = AdrianRemembersMe()     
        resetlink = arm.getresetlinkfromcode(code)
        if resetlink:
            template_values['code'] = code
            #Validate Form
            if request.method == "POST":
                password = request.REQUEST['password']
                password2 = request.REQUEST['password2']
                if password == '' or password != password2:
                    template_values['error'] = 'Please make sure passwords match and are not empty.'
                #Reset Password
                else:
                    success = arm.resetpassword(resetlink,password)
                    if success:
                        template_values['success'] = True
                    else:
                        template_values['error'] = 'There was an error while resetting your password. Please try again.'
                        
    return render_to_response(template, template_values)

def encryptpasswords(request):
    template = "encryptpasswords.html"
    template_values = {}
    
    arm = AdrianRemembersMe()
    success = arm.encryptpasswords()
    if success:
        template_values['message'] = 'Encryption succeeded. All passwords are now encrypted'
    else:
        template_values['message'] = '''Encryption failed. Make sure you have ENCRYPTED_PASSWORDS
        value set to True in adrianremembersmeapp/armsettings.py'''
    return render_to_response(template, template_values)
